import threading
import sounddevice as sd
import numpy as np
import wave
import logging
import asyncio
import os

class AudioProcessor:
    def __init__(self):
        self.is_recording = False
        self.audio_data = []

    # 开始录音函数
    def start_recognition(self):
        self.is_recording = True
        self.audio_data = []

        def record_audio():
            try:
                with sd.InputStream(channels=1, samplerate=16000, dtype='int16') as stream:
                    while self.is_recording:
                        data, _ = stream.read(1024)
                        self.audio_data.append(data)
            except Exception as e:
                logging.error("录音时发生错误：%s", e)

        threading.Thread(target=record_audio).start()
        return "正在录音，请开始讲话..."

    # 结束录音并处理音频函数
    def stop_recognition(self, config):
        self.is_recording = False

        if not self.audio_data:
            logging.error("没有录制到音频数据。")
            return "录音失败，没有录制到音频数据。"

        audio_file_path = "recorded_audio.wav"
        audio_data_np = np.concatenate(self.audio_data, axis=0)
        with wave.open(audio_file_path, 'wb') as wf:
            wf.setnchannels(1)
            wf.setsampwidth(2)  # 16位音频
            wf.setframerate(16000)
            wf.writeframes(audio_data_np.tobytes())

        if os.path.getsize(audio_file_path) == 0:
            logging.error("录制的音频文件为空。")
            return "录音失败，音频文件为空。"

        # 使用异步方式调用语音识别
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        from modules.speech_to_text import speech_to_text
        recognized_text = loop.run_until_complete(speech_to_text(audio_file_path, config))
        loop.close()

        if not recognized_text:
            return "语音识别失败或未识别到有效的语音内容。"

        return recognized_text